package com.cn.shuangzi.userinfo.activity;

import android.app.Activity;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.SZBaseActivity;
import com.cn.shuangzi.SZBaseWebActivity;
import com.cn.shuangzi.activity.SZInterfaceActivity;
import com.cn.shuangzi.bean.VipPriceInfo;
import com.cn.shuangzi.common.SZConst;
import com.cn.shuangzi.loginplugin.common.socialized.pay.PayManager;
import com.cn.shuangzi.loginplugin.common.socialized.pay.PayType;
import com.cn.shuangzi.retrofit.SZCommonResponseListener;
import com.cn.shuangzi.retrofit.SZRetrofitManager;
import com.cn.shuangzi.userinfo.R;
import com.cn.shuangzi.util.SZTextViewWriterUtil;
import com.cn.shuangzi.util.SZToast;
import com.cn.shuangzi.util.SZUtil;

import java.util.UUID;

/**
 * Created by CN.
 */

public abstract class SZPayVipOldActivity extends SZBaseActivity implements View.OnClickListener, SZInterfaceActivity {
    public TextView txtName;
    public TextView txtPrice;
    public TextView txtDesc;
    public Button btnPay;
    public CheckBox chkBoxAgree;
    public ImageView imgCheckWechat;
    public ImageView imgCheckAlipay;
    public String payType = SZConst.ALIPAY;
    public VipPriceInfo vipPriceInfoCheck;
    public TextView txtContactService;
    private String email;

    @Override
    protected int onGetChildView() {
        return R.layout.activity_pay_old;
    }

    @Override
    protected void onBindChildViews() {

        txtName = findViewById(R.id.txtName);
        txtPrice = findViewById(R.id.txtPrice);
        txtDesc = findViewById(R.id.txtDesc);
        btnPay = findViewById(R.id.btnPay);
        imgCheckWechat = findViewById(R.id.imgCheckWechat);
        imgCheckAlipay = findViewById(R.id.imgCheckAlipay);
        txtContactService = findViewById(R.id.txtContactService);
        chkBoxAgree = findViewById(R.id.chkBoxAgree);

    }

    @Override
    protected void onBindChildListeners() {

    }

    @Override
    protected void onChildViewCreated() {
        onChildViewCreatedPre();
        showBackImgLeft(getBackImgLeft());
        setTitleTxt("支付订单");
        vipPriceInfoCheck = getSerializableExtra();
        if (vipPriceInfoCheck == null) {
            finish();
            return;
        }
        email = getEmail();
        if (email == null) {
            email = "service@shuangzikeji.cn";
        }

        String desc = getString(R.string.txt_pay_contact, email);
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(desc);
        stringBuilder.setSpan(new DescTextViewSpan(),
                desc.indexOf(email), desc.indexOf(email) + email.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        txtContactService.setText(stringBuilder);
        txtContactService.setHighlightColor(getResources().getColor(android.R.color.transparent));
        txtContactService.setMovementMethod(LinkMovementMethod.getInstance());
        SZTextViewWriterUtil.writeValue(txtName, vipPriceInfoCheck.getFpSubject());
//        SZTextViewWriterUtil.writeValue(txtDesc, vipPriceInfoCheck.getFpOriginalPrice() + "元/月");
        SZTextViewWriterUtil.writeValue(txtPrice, vipPriceInfoCheck.getFpPrice());
    }

    @Override
    protected void onReloadData(boolean isRefresh) {

    }

    private void submitOrder() {
        btnPay.setEnabled(false);
        showBar();
        String uuid = null;
        try {
            uuid = UUID.randomUUID().toString().replace("-", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        request(SZRetrofitManager.getInstance().getSZRequest().submitOrderV2(getUserId(), payType, uuid, vipPriceInfoCheck.getFpId()), new SZCommonResponseListener() {
            @Override
            public void onResponseSuccess(String data) {
                new PayManager(getActivity(), SZConst.ALIPAY.equals(payType) ? PayType.ALIPAY : PayType.WECHAT, data, new PayManager.OnPayListener() {
                    @Override
                    public void onPaySuccess() {
                        closeBar();
                        try {
                            for (Activity activity : SZApp.getInstance().getStackActivity()) {
                                if (activity instanceof SZBuyVipActivity) {
                                    activity.finish();
                                    break;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        startActivity(getSynchronizeVipClass());
                        finish();
//                        onPayDoneSuccess(payType);
//                        requestVipUserInfo(getVipUserObservable());
//                        try {
//                            SweetAlertDialog sweetAlertDialog = showAlert(SweetAlertDialog.SUCCESS_TYPE, "支付成功", "恭喜您，已成功购买" + vipPriceInfoCheck.getFpSubject(), "确定", new SweetAlertDialog.OnSweetClickListener() {
//                                @Override
//                                public void onClick(SweetAlertDialog sweetAlertDialog) {
//                                    sweetAlertDialog.dismissWithAnimation();
//                                    finish();
//                                }
//                            }, null, null, false);
//                            sweetAlertDialog.setCancelable(false);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
                    }

                    @Override
                    public void onPayCancel() {
                        closeBar();
                        btnPay.setEnabled(true);
                        SZToast.warning("您取消了支付!");
                    }

                    @Override
                    public void onPayFailed() {
                        closeBar();
                        btnPay.setEnabled(true);
                        SZToast.error("支付失败,请重试!");
                    }
                }).toPay();
            }

            @Override
            public void onResponseError(int errorCode, String errorMsg) {
                btnPay.setEnabled(true);
                closeBar();
            }
        });
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.btnPay) {
            if (getUserId() == null) {
                startActivity(getLoginClass());
            } else {
                if (chkBoxAgree.isChecked()) {
                    submitOrder();
                } else {
                    SZUtil.showAgreeProtocolAlert(this, "同意并购买", getString(R.string.vip_service_agreement_symbol),
                            getVipProtocolUrl(), getWebViewActivity(),
                            new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    chkBoxAgree.setChecked(true);
                                    submitOrder();
                                }
                            });
                }
            }
        } else if (viewId == R.id.rltWechatPay) {
            payType = SZConst.WXPAY;
            imgCheckWechat.setImageResource(R.mipmap.pay_icon_choose);
            imgCheckAlipay.setImageResource(R.mipmap.pay_icon_not);
        } else if (viewId == R.id.rltAlipay) {
            payType = SZConst.ALIPAY;
            imgCheckAlipay.setImageResource(R.mipmap.pay_icon_choose);
            imgCheckWechat.setImageResource(R.mipmap.pay_icon_not);
        } else if (viewId == R.id.txtVipProtocol) {
            startActivity(getVipProtocolUrl(), getWebViewActivity());
        }
    }

//    public void requestVipUserInfo(Observable<String> observable) {
//        SZRetrofitManager.getInstance().request(observable, "vip", new SZCommonResponseListener() {
//            @Override
//            public void onResponseSuccess(String data) {
//                List<VipInfo> vipInfoList = new Gson().fromJson(data, new TypeToken<List<VipInfo>>() {
//                }.getType());
//                if (SZValidatorUtil.isValidList(vipInfoList)) {
//                    vipInfoBought = vipInfoList.get(0);
//                } else {
//                    vipInfoBought = null;
//                }
//                setVipUserInfo(vipInfoBought);
//            }
//            @Override
//            public void onResponseError(int errorCode, String errorMsg) {
//
//            }
//        });
//    }

    private class DescTextViewSpan extends ClickableSpan {
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(getResources().getColor(com.cn.shuangzi.userinfo.R.color.colorNotesEmail));
            ds.setUnderlineText(false);
        }

        @Override
        public void onClick(View widget) {
            SZUtil.copyClipboard(getActivity(), email);
            SZToast.success("邮箱地址已复制到剪贴板！");
        }
    }

    public abstract String getUserId();

    public abstract String getEmail();

    public abstract Class<?> getLoginClass();

    public abstract Class<?> getSynchronizeVipClass();

    public abstract String getVipProtocolUrl();

    public abstract Class<? extends SZBaseWebActivity> getWebViewActivity();
}
